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,080,626
14,104,321
Numpy: improve arrays operations
<p>As an example, I have the 2 following 1d-arrays:</p> <pre><code>import numpy as np a = np.array([1, 2, 3, 4]) b = np.array([5, 6]) </code></pre> <p>Now, I need to multiply <code>a</code> for each element of <code>b</code> in order to obtain a 2d-array:</p> <pre><code>[[5 10 15 20], [6 12 18 24]] </code></pre> <p>...
<python><arrays><numpy>
2023-01-11 09:12:32
4
582
mauro
75,080,477
8,033,003
ImportError when running watson machine learning locally
<p>I am trying to communicate with Watson Machine Learning from my local windows machine using vscode to run a jupyter notebook in a virtual enviroment but I cannot get it to work.</p> <p>I installed</p> <pre><code>!pip install tensorflow !pip install ibm_watson_machine_learning </code></pre> <p>I created and trained a...
<python><tensorflow><ibm-cloud><ibm-watson><watson-ml>
2023-01-11 08:58:08
2
693
Maximilian Jesch
75,080,439
10,202,292
Disallow passing f-strings as argument
<p>I am reporting data from some tests, and each test can have a 'summary' and a 'details' section. The 'summary' field for any particular test should be static, with any additional dynamic information going into the details field, as follows:</p> <pre><code>run_test() if condition: report_test_data(summary=&quot;con...
<python><pylint><f-string>
2023-01-11 08:55:21
1
403
tigerninjaman
75,080,380
15,307,844
Why/when is numpy.equal() 10x faster when working with x.T.copy() instead of x.T?
<p><strong>Context:</strong> I made the following observations when trying to optimize my code for speed. It involves the use of large square matrices with up to 3.6e9 elements (assuming I can speed it up sufficiently ...).</p> <p><strong>Observations:</strong> Consider a square numpy array <code>x</code>. Doing <code>...
<python><numpy><performance>
2023-01-11 08:50:44
0
441
fpavogt
75,080,340
10,413,550
Pytest not able to run test where script A importing another script B in the same folder level as A and giving me ModuleNotFoundError
<p>I am trying to run the unit test using pytest in this project, here main_0.py is importing s3 file.</p> <p>I am getting <code>ModuleNotFoundError: no module named 's3'</code></p> <p>Project Folder Structure</p> <pre><code> some_project └───src β”œβ”€β”€β”€main β”‚ └───lambda_function β”‚ β””...
<python><python-3.x><unit-testing><pytest><python-unittest>
2023-01-11 08:46:43
2
393
SKJ
75,080,119
6,054,404
Freezing code and including .libs folders
<p>I have a successful build of a python 3.9 program I'm working on. However, the following folders need to be manually copied into the lib folder;</p> <ul> <li>pyproj.libs</li> <li>scipy.libs</li> <li>Shapely.libs</li> </ul> <p>I have the setup.py, how do I set it up so that these folders are copied to the correct loc...
<python><cx-freeze>
2023-01-11 08:25:54
0
1,993
Spatial Digger
75,080,042
7,074,969
ModuleNotFoundError: No module named 'Cython' even though Cython is installed in Azure Devops
<p>I'm setting up some CI/CD for a Python app (Azure Function) using Azure Devops and I've stumbled upon an issue with one of the requirements. The error I receive is <strong>ModuleNotFoundError: No module named 'Cython'</strong> while trying to install <code>pymssql-2.1.4</code>. Before this requirement, I have set a ...
<python><azure-devops><azure-functions><requirements.txt>
2023-01-11 08:17:25
1
1,013
anthino12
75,079,985
5,342,009
How to change subscription from PlanA to PlanB using Stripe with Python/Django
<p>I can create a Stripe subscription for a customer using the following code :</p> <pre><code> subscription = stripe.Subscription.create( customer=stripe_customer_id, items=[ { &quot;plan&quot;: stripe_plan_A }, ] ) </code></pre...
<python><django><stripe-payments>
2023-01-11 08:11:56
2
1,312
london_utku
75,079,735
5,641,924
Logs 100K request per second in real-time with python logging package
<p>I have to get the data from one of my localhost ports and saved it to a log file. To do this, I use the <code>logging</code> package. Here is my code:</p> <ol> <li><p>In the first step I designed my custom <code>TimedRotatingFileHandler</code>:</p> <pre><code>from logging.handlers import BaseRotatingHandler, TimedR...
<python><logging><syslog>
2023-01-11 07:46:28
0
642
Mohammadreza Riahi
75,079,637
216,229
type annotation for return type of method where that depends on an attribute of the class
<p>Say I have:</p> <pre class="lang-py prettyprint-override"><code>class A: pass class B: pass class Foo: factory: Type = A def make(self) -&gt; ?: return self.factory() class Bar(Foo): factory: Type = B </code></pre> <p>What type annotation do I use on make to indicate that the type returned is th...
<python>
2023-01-11 07:35:48
1
11,138
Chris Withers
75,079,329
1,397,922
How to properly open and encode CSV file in Python to be processed in Odoo framework
<p>I tried to import a CSV file in Odoo custom module, but my logic stopped at some point where I decode the file object. Below is my code:</p> <pre class="lang-py prettyprint-override"><code>def import_csv(self, csv_file): reader = csv.reader(csv_file) next(reader) for row in reader: record = { ...
<python><csv><odoo><decode><encode>
2023-01-11 06:59:42
1
550
Andromeda
75,079,183
19,834,019
Bulk insert on multi-column unique constraint Django
<p>Suppose we have a model</p> <pre><code>from django.db import models class Concept(models.Model): a = models.CharField(max_length=255) b = models.CharField(max_length=255) c = models.CharField(max_length=255) d = models.CharField(max_length=255) class Meta: constraints = [ mo...
<python><sql><django><sqlite>
2023-01-11 06:42:14
1
303
Ambiguous Illumination
75,079,148
425,964
Python logging stdout and stderr based on level
<p>Using Python 3 logging, how can I specify that <code>logging.debug()</code> and <code>logging.info()</code> should go to <code>stdout</code> and <code>logging.warning()</code> and <code>logging.error()</code> go to <code>stderr</code>?</p>
<python><python-3.x><logging>
2023-01-11 06:36:37
2
45,778
Justin
75,079,092
1,236,858
Poetry: Disabling SSL certification check
<p>I'm trying to disable SSL certification check for self-signed certificate using example mentioned in : <a href="https://python-poetry.org/docs/repositories/#certificates" rel="nofollow noreferrer">https://python-poetry.org/docs/repositories/#certificates</a></p> <pre><code>poetry config certificates.foo.cert false <...
<python><python-poetry>
2023-01-11 06:30:40
0
7,307
rcs
75,078,992
8,874,837
Get key hierarchy from a nested dict of other lists/dicts in Python
<p>I have an input dict like so:</p> <pre><code>input={'boo': 'its', 'soo': 'your', 'roo': 'choice', 'qoo': 'this', 'fizz': 'is', 'buzz': 'very', 'yoyo': 'rambling', 'wazzw': 'lorem', 'bnn': 'ipsum', 'cc': [{'boo': 'fill', 'soo': 'ing', 'roo': 'in', 'qoo': 'the', 'fizz': 'words', 'buzz': 'here', 'yoyo': 'we', 'wazzw': ...
<python><list><dictionary>
2023-01-11 06:16:58
3
350
tooptoop4
75,078,868
9,376,425
use Scalene for FastAPI profiling
<p>I'm currently trying to profile my FastAPI endpoints using Scalene. my code looks like this. I have a profiling middleware like this:</p> <pre class="lang-py prettyprint-override"><code>class ScaleneProfilerMiddleware(BaseHTTPMiddleware): def __init__(self, app): super().__init__(app) async def dis...
<python><profiling><profiler><scalene>
2023-01-11 06:00:35
0
424
Mahdi Sorkhmiri
75,078,513
14,551,577
How to download sub pages linked by javascript function in selenium python
<p>I am going to download all pages linked by javascript function.<br /> The HTML structure is following.</p> <p><code>index.html</code>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type=&quot;text/javascript&quot;&gt; function a(){ document.location = 'a.html' } ...
<python><selenium><selenium-webdriver><web-scraping>
2023-01-11 05:00:47
0
644
bcExpt1123
75,078,486
14,627,589
Unexpected end of template. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'
<p>I have visited these answers too <a href="https://stackoverflow.com/questions/49822676/running-flask-environment-using-htmlreceiving-error-message-of-expected-else-st">Running Flask environment using HTML:receiving error message of expected else statement</a> and <a href="https://stackoverflow.com/questions/55933020...
<python><jinja2>
2023-01-11 04:53:35
1
551
ARHAM RUMI
75,078,418
1,157,639
Passing **kwargs arguments to parent classes in multiple inheritance loses kwargs content
<p>In a multiple inheritance scenario, how does Python3 pass the arguments to all the parent classes? Consider the toy program below:</p> <pre><code>class A(object): def __init__(self, a='x', **kwargs): print('A', kwargs) super().__init__() class B(object): def __init__(self, **kwargs): ...
<python><multiple-inheritance>
2023-01-11 04:42:08
1
776
Anshul
75,078,361
15,542,245
Skewing text - How to take advantage of existing edges
<p>I have the following JPG image. If I want to find the edges where the white page meets the black background. So I can rotate the contents a few degrees clockwise. My aim is to straighten the text for using with Tesseract OCR conversion. I don't see the need to rotate the text blocks as I have seen in similar example...
<python><ocr><canny-operator><image-thresholding>
2023-01-11 04:31:19
1
903
Dave
75,078,287
10,035,190
how to make multiselecte dropdown field in flask?
<p>I am trying to make a multiselecte dropdown field with clear button in flask like this.</p> <p><a href="https://i.sstatic.net/SeBBv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SeBBv.png" alt="enter image description here" /></a></p> <p>I have tried this but not working the way I want</p> <pre><cod...
<python><flask><wtforms>
2023-01-11 04:18:23
2
930
zircon
75,078,242
13,659,567
How to generate a PNG image in PIL and display it in Jinja2 template using FastAPI?
<p>I have a FastAPI endpoint that is generating PIL images. I want to then send the resulting image as a stream to a Jinja2 <code>TemplateResponse</code>. This is a simplified version of what I am doing:</p> <pre class="lang-py prettyprint-override"><code>import io from PIL import Image @api.get(&quot;/test_image&qu...
<python><jinja2><python-imaging-library><fastapi>
2023-01-11 04:07:32
2
365
Brad Allen
75,078,174
4,935,567
Instagram follower and following count mismatch
<p>When scraping the Instagram profile page of an account, it shows 3 numbers: posts, followers, and following. There is a request to Instagram's APIs that corresponds to these numbers.</p> <p>If you look at the other request which loads the account's page itself (a document-type request), in the meta tags there's a me...
<python><web-scraping><instagram>
2023-01-11 03:50:00
1
2,618
Masked Man
75,078,125
2,463,570
Panda merge all columns start with a prefix "result"
<p>I have a dynamic dataframe generation which create column or columns like below x,y,z, can be anything</p> <p>df</p> <pre><code> result result_x result_y result_z result_..... 0 1 1 0 0 1 0 1 </code></pre> <p>some...
<python><pandas>
2023-01-11 03:37:23
1
12,390
Rajarshi Das
75,078,108
5,212,614
Struggling with geopy install. ModuleNotFoundError: No module named 'geopy.geocoders'
<p>I ran <code>pip install geopy</code> and it seemed to install ok, but I couldn't run the following script.</p> <pre><code>from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent=&quot;ryan_data&quot;) location = geolocator.geocode(&quot;175 5th Avenue NYC&quot;) print(location.address) </code></pre> ...
<python><python-3.x><geopy>
2023-01-11 03:33:46
1
20,492
ASH
75,077,884
2,377,957
Implement pkg_resources.resource_filename in setuptools
<p>I am working to incorporate the symspellpy package for spell checking and correcting large amounts of data. However, the package suggests using pkg_resources.resource_filename, which is no longer supported. Can you please provide guidance on how to access the necessary resources using the currently preferred method?...
<python><pkg-resources><symspellpy>
2023-01-11 02:50:44
1
4,105
Francis Smart
75,077,578
4,045,121
Lazy file reader that yields one line at a time
<p>I want to build a class that can be used like this:</p> <pre><code>d = Data(file_name) line = next(d) # or for line in d: print(line) </code></pre> <p>I have this class:</p> <pre><code>@dataclass class Data: file_name: str data: IO = field(default=None) def __post_init__(self): self._data = ...
<python>
2023-01-11 01:50:45
1
3,452
dearn44
75,077,537
1,887,277
"Vectorized" Matrix-Vector multiplication in numpy
<p>I have an $I$-indexed array $V = (V_i)_{i \in I}$ of (column) vectors $V_i$, which I want to multiply pointwise (along $i \in I$) by a matrix $M$. So I'm looking for a &quot;vectorized&quot; operation, wherein the individual operation is a multiplication of a matrix with a vector; that is</p> <p>$W = (M V_i)_{i \in ...
<python><numpy><vectorization><linear-algebra>
2023-01-11 01:43:16
2
722
Mark
75,077,412
6,283,073
How to generate embeddings of object images detected with YOLOv5?
<p>I want to run real time object detection using YOLOv5 on a camera and then generate vector embeddings for cropped images of detected objects.</p> <p>I currently generate image embeddings using this function below for locally saved images:</p> <pre class="lang-py prettyprint-override"><code>def generate_img_embedding...
<python><yolo><embedding>
2023-01-11 01:12:11
1
1,679
e.iluf
75,077,369
14,575,973
How to import module using path related to working directory in a python project that managed by poetry?
<p>I'm using poetry to manage my python project, here's the project:</p> <pre><code>my_project/ β”œβ”€β”€ pyproject.toml β”œβ”€β”€ module.py └── scripts/ └── main.py </code></pre> <p>And I want to know how to import function from <code>module.py</code> into <code>my_scripts/main.py</code> correctly.</p> <p>My pyproject.toml:</...
<python><python-import><python-module><python-packaging><python-poetry>
2023-01-11 01:01:51
3
1,020
Matt Peng
75,077,337
6,611,672
Use Django ORM in locust
<p>I'm using locust to load test my Django application. I'm currently hardcoding certain values in my <code>locustfile.py</code>:</p> <pre><code>GROUP_UUID = &quot;6790f1e6-64f9-4707-aa82-d4edd64c9cc7&quot; @task def get_single_group(self): self.client.get(f&quot;/api/groups/{GROUP_UUID}/&quot;) </code></pre> <p>T...
<python><django><locust>
2023-01-11 00:52:39
1
5,847
Johnny Metz
75,077,283
872,009
Append element to column with numpy.ndarray datatype in Pandas
<p>I want to append a string to a column which is a numpy.ndarray object.The following code is not working:</p> <pre><code>def filter_by_player(df, players, team): filtered_df = df[df['player'].isin(players)] filtered_df['league'] = filtered_df['league'].apply(lambda x: x + [team]) return filtered_df </code...
<python><pandas><list><dataframe>
2023-01-11 00:38:57
1
438
user872009
75,077,247
4,930,299
Dynamically renaming attributes of a python class?
<p>I am working with a beta version of a python library that has renamed a few of the class functions, for instance from &quot;isConnected&quot; to &quot;is_connected&quot;. I have different servers with different versions of this library on them and it tends to get annoying to deal with. So far I have till now been de...
<python><attributes>
2023-01-11 00:32:06
0
343
Chev_603
75,077,179
1,029,902
div not showing up in html from url using requests library and bs4
<p>I have a simple script where I want to scrape a menu from a url:</p> <p><a href="https://untappd.com/v/glory-days-grill-of-ellicott-city/3329822" rel="nofollow noreferrer">https://untappd.com/v/glory-days-grill-of-ellicott-city/3329822</a></p> <p>When I inspect the page using dev tools, I identify that the menu cont...
<python><web-scraping><beautifulsoup><python-requests>
2023-01-11 00:17:31
1
557
Tendekai Muchenje
75,077,028
5,463,912
How to create summary statistics for an entire SQLite data base?
<p>Consider some SQLite database.db, with a large number of tables and columns.</p> <p>Panda's <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.describe.html" rel="nofollow noreferrer">.describe()</a> produces the summary statistics that I want (see below). However, it requires reading each table ...
<python><sqlite>
2023-01-10 23:53:25
1
314
CFW
75,077,008
7,204,831
pytest using global package despite using virtual env
<p>Situation: on the linux PC, the global package version installed: x.y.z In the project directory, requirements.txt specifies a.b.c version for package. a.b.c &gt; x.y.z there is a bash script in the directory that sets up a virtual environment, installs the packages from requirements.txt in that virtual environment,...
<python><package><pytest><virtualenv>
2023-01-10 23:49:28
2
383
Samyukta Ramnath
75,076,887
13,119,030
Display output of numpy array on full length of screen
<p>I want to display the output of a numpy array in PyCharm such that the output is printed on a single line. So I don't want that the output characters are split up into two lines as the example below. I want all the characters of the numpy array on the same line. Not like below:</p> <pre><code>[ 0. 0. 0. 0. 0. 1...
<python><arrays><numpy><pycharm><display>
2023-01-10 23:26:42
1
540
Pieter-Jan
75,076,748
14,509,604
Can't query Twitter API v2 with elevated acces project/app
<p>I'm trting to query Twitter API v2 with elevated research access via tweepy, but it still gives me a <code>403 Forbidden</code>. <a href="https://i.sstatic.net/ZvIhv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZvIhv.png" alt="evelevated acces proof of my app" /></a></p> <pre class="lang-py prettyp...
<python><twitter><tweepy>
2023-01-10 23:05:34
1
329
juanmac
75,076,741
2,679,223
Numpy indexing oddity: How to subselect from multidimensional array and keep all axes
<p>I have a multi-dimensional array, and have two lists of integers, L_i and L_j, corresponding to the elements of axis-i and axis-j I want to keep. I also want to satisfy the following:</p> <ol> <li>Keep original dimensionality of the array, even if L_i or L_j consists of just 1 element (in other words I dont want a s...
<python><arrays><numpy>
2023-01-10 23:05:00
2
1,294
bigO6377
75,076,678
1,839,555
Overriding a method when creating a new object
<p>I'm using the <a href="https://pypi.org/project/watchdog/" rel="nofollow noreferrer">Watchdog library</a> to monitor different folders. There are two folders with two different behaviors:</p> <ol> <li>In folder <code>alpha</code>, when a new file is created, move it to <code>destination_alpha</code>.</li> <li>In fol...
<python><inheritance><overriding>
2023-01-10 22:54:56
1
1,508
Bagheera
75,076,523
3,462,509
Python DFS (CS 188 Berkeley Pacman)
<p>I am not a Berkeley student, I'm just taking this course for fun (so you aren't helping me cheat). I've implemented their <a href="https://inst.eecs.berkeley.edu/%7Ecs188/fa18/project1.html" rel="nofollow noreferrer">project 1</a>, but I am failing the autograder for Question 1 (DFS) and only question 1. I'm alway...
<python><artificial-intelligence><depth-first-search>
2023-01-10 22:29:17
1
2,792
Solaxun
75,076,441
8,065,797
retrieving xml element value by searching the element by substring in its name
<p>I would need to retrieve xml element value by searching the element by substring in its name, eg. I would need to get value for all elements in XML file which names contains <code>client</code>.</p> <p>I found a way how to find element with xpath by an attribute, but I haven't find a way for element name.</p>
<python><xpath><lxml><elementtree>
2023-01-10 22:17:53
1
529
JanFi86
75,075,770
5,024,631
Python while loop continues beyond the while condition
<p>My while loop doesn't stop when it's supposed to. Obviously there's something fundamental I'm missing here.</p> <p>Here is my code:</p> <pre><code>import time import datetime import pandas as pd period = 5 start = pd.to_datetime('2022-01-01') end_final = pd.to_datetime('2022-01-31') sd = start while start &lt; end_f...
<python><date><while-loop>
2023-01-10 20:58:32
2
2,783
pd441
75,075,754
12,226,377
Using pandas to identify which are the 5 point and 10 point scale survey questions in a dataframe
<p>I have a unique situation where my dataset contains multiple survey responses that were asked on two different scales primarily - a 5 point scale and then a 10 point scale and I have consolidated all of these responses in one dataframe. Now I would like to split and create a new column in my dataframe that can tell ...
<python><pandas><survey>
2023-01-10 20:56:18
2
807
Django0602
75,075,713
3,738,936
Cannot Insert Pandas dataframe in to PGsql with Python
<p>I am trying to use a pandas dataframe to insert data to sql. I am using pandas because there are some columns that I need to drop before I insert it into the SQL table. The database is in the cloud, but that isn't the issue. I've been able to create static strings, insert them in the the database &amp; it works fine...
<python><pandas><postgresql><sqlalchemy>
2023-01-10 20:52:59
1
986
Don M
75,075,546
12,983,543
"celery": executable file not found in $PATH
<p>I am trying to make my Django redis celery project on with <code>docker-compose</code>, but there is no way it is starting. Here is the docker-compose file</p> <pre><code>version: &quot;3.9&quot; services: db: container_name: my_table_postgres image: postgres ports: - 5432/tcp volumes: ...
<python><docker><celery>
2023-01-10 20:35:41
2
614
Matteo Possamai
75,075,284
2,817,520
What are the caveats of namespace packages
<p>Here in <a href="https://packaging.python.org/en/latest/guides/packaging-namespace-packages/" rel="nofollow noreferrer">Packaging namespace packages</a>, it is mentioned that</p> <blockquote> <p>namespace packages can be useful for a large collection of loosely-related packages (such as a large corpus of client libr...
<python><packaging>
2023-01-10 20:06:48
1
860
Dante
75,075,246
1,418,326
Pickle Load Custom Object Parameters Misaligned
<p>Car.py:</p> <pre><code> class Car(object): def __init__(self, year=2023, speed=50): self.year = year self.speed = speed self.word_index = {} </code></pre> <p>Util.py:</p> <pre><code>from custom.Car import Car c1 = Car(2020, 40) picklefile = open('car.pkl', 'wb') pickle....
<python><pickle>
2023-01-10 20:02:11
1
1,707
topcan5
75,075,234
6,392,779
Regex to match first occurrence of non alpha-numeric characters
<p>I am parsing some user input to make a basic Discord bot assigning roles and such. I am trying to generalize some code to reuse for different similar tasks (doing similar things in different categories/channels).</p> <p>Generally, I am looking for a substring (the category), then taking the string after as that cate...
<python><regex>
2023-01-10 20:00:55
2
901
nick
75,075,099
12,014,637
TypeError: Failed to convert elements of (None, -1, 3, 1) to Tensor. Consider casting elements to a supported type
<p>I have a custom tensorflow layer which works fine by generating an output but it throws an error when used with the Keras functional API. Here is the code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.la...
<python><tensorflow><keras><deep-learning>
2023-01-10 19:46:39
0
618
Amin Shn
75,075,084
13,488,334
PyTest - Specify cleanup tests in conftest.py
<p>I am testing a service that requires starting and shutting down a gRPC server via a client's request. In my set of integration tests, I need to specify a set of pre-test and post-test actions that should happen before any given test is run within the set. Ideally, I would like to keep these pre/post-test methods in ...
<python><pytest><integration-testing>
2023-01-10 19:45:25
1
394
wisenickel
75,075,061
2,817,520
Python namespace-subpackage naming convention
<p>According to <a href="https://peps.python.org/pep-0008/#package-and-module-names" rel="nofollow noreferrer">PEP 8 – Style Guide for Python Code</a>, Python packages should also have short, all-lowercase names, <strong>although the use of underscores is discouraged</strong>. But <a href="https://packaging.python.org/...
<python>
2023-01-10 19:42:49
0
860
Dante
75,074,877
3,040,845
Get 'Can't get attribute" error while loading my pickel file
<p>I am trying to use pick to save and load my ML models but I get an error. Here is the simplify version of my code to save my model:</p> <pre><code>import pickle def test(x,y): return x+y filename = 'test.pkl' pickle.dump(test, open(filename, 'wb')) </code></pre> <p>I can load the pickle file from the same noteb...
<python><pickle>
2023-01-10 19:23:19
1
1,097
Amir
75,074,870
7,158,458
Using multi threading to simulate 6 users logging in using Selenium
<p>I am trying to create a function using selenium to login to a page in a different tab for each credential in a dictionary of usernames and passwords. I have 6 users so I will have 6 tabs open. I want to keep track of each tab I have open so I can navigate back to a specific tab.</p> <p>This is what I have tried:</p>...
<python><selenium><selenium-webdriver>
2023-01-10 19:22:39
0
2,515
Emm
75,074,766
1,974,918
polars groupby on categorical produces nulls
<p><strong>Update:</strong> This issue is no longer present. The query produces the expected values.</p> <hr /> <p>I ran into an issue with polars where after a groupby on a categorical variable the labels are null</p> <pre class="lang-py prettyprint-override"><code>import polars as pl scores = pl.DataFrame({ 'zon...
<python><python-polars>
2023-01-10 19:11:57
0
5,289
Vincent
75,074,596
7,437,221
PuLP linear programming problem is infeasible
<p>I am writing a Linear Programming problem to help generate daily fantasy lineups.</p> <p>The goal is:</p> <ul> <li>Maximize Fpts projection</li> </ul> <p>The constraints are:</p> <ul> <li>Salary (Maximum 50,000)</li> <li>Positionality (Have to have 1 PG, 1 SG, 1 SF, 1 PF, 1 C, 1 G, 1 F and 1 UTIL player) where &quot...
<python><data-science><linear-programming><pulp>
2023-01-10 18:55:38
1
353
Sean Sailer
75,074,524
4,939,983
Why does python list resize overallocation differ from other languages?
<p>I've been reading a bit of python source code and found a <a href="https://hg.python.org/releasing/3.4.2/file/10298f4f42dc/Objects/listobject.c#l25" rel="nofollow noreferrer">peculiar comment about the resize overallocation strategy</a> -</p> <pre><code>/* This over-allocates proportional to the list size, making ro...
<python><arrays><memory-management><cpython>
2023-01-10 18:47:49
0
334
Shu ba
75,074,499
4,157,666
Sagemaker: read-only file system: /opt/ml/models/../config.json when invoking endpoint
<p>Trying to create a Multi Model with sagemaker. Doing the following:</p> <pre><code>boto_seasson = boto3.session.Session(region_name='us-east-1') sess = sagemaker.Session(boto_session=boto_seasson) iam = boto3.client('iam') role = iam.get_role(RoleName='sagemaker-role')['Role']['Arn'] huggingface_model = HuggingFac...
<python><amazon-web-services><boto3><amazon-sagemaker>
2023-01-10 18:45:09
1
5,031
Mpizos Dimitris
75,074,493
10,481,744
Find all the possible combinations of the numbers in the column of pandas dataframe that sum to 0
<p>I have a dataframe with 10000 rows..I want to find all the combinations of rows where the values in particular column (Amount) sums to 0.</p> <p>df=</p> <pre><code>ID_Key Amount 10 12.4 12 -26.6 13 14.2 14 15 17 4.5 18 ...
<python><pandas>
2023-01-10 18:44:00
1
340
TLanni
75,074,474
4,960,470
RPi.GPIO: defined output pin not found in /sys/class/gpio
<p>I have a python3 script which uses RPi.GPIO and defines 2 input pins and 1 output pin like shown below</p> <pre><code>GPIO.setmode( GPIO.BCM ) # init GPIOs GPIO.setup( 2, GPIO.IN, pull_up_down=GPIO.PUD_UP ) GPIO.setup( 3, GPIO.IN, pull_up_down=GPIO.PUD_UP ) GPIO.setup( 4, GPIO.OUT ) </code></pre> <p>...
<python><gpio>
2023-01-10 18:41:05
1
587
user333869
75,074,458
1,215,291
Change directory in python - os.chdir('/tmp') vs os.system("cd " + backup_location)
<p>I'm experimenting with using Python for backups, because my Bash script became too big and complicated. I'm totally new in Python, I'm not fan of it, but it seems like Python is perfect tool for such complicated scripts.</p> <p>I have found something to start with on Github:</p> <p><a href="https://github.com/Tutori...
<python><filesystems><python-3.9>
2023-01-10 18:39:40
1
14,043
Kamil
75,074,445
4,913,660
Pandas unexpectedly casts type in heterogeneous dataframe
<p>if I define a dataframe like this</p> <pre><code>import numpy as np import pandas as pd str1= [&quot;woz&quot;, &quot;baz&quot;, &quot;fop&quot;, &quot;jok&quot;] arr=np.array([2,3,4]) data = {&quot;Goz&quot;:str1, &quot;Jok&quot;: np.hstack((np.array([5,&quot;fava&quot;]), np.array ([1,2]) ) ) } df = pd.DataFrame(d...
<python><pandas><numpy>
2023-01-10 18:38:22
0
414
user37292
75,074,394
10,043,234
Django password reset PasswordResetConfirmView
<p>View:</p> <pre><code>def f_forget_password(request): ctx = dict() if request.method == &quot;POST&quot;: password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): to_email = password_reset_form.cleaned_data['email'] to_email=to_email.lowe...
<python><django><django-views><passwords><reset-password>
2023-01-10 18:33:55
0
311
mohamadreza ch
75,074,339
7,050,517
VSCode Python Remote Debugging Suddenly Not Working
<p>Starting a couple days ago my normal process for debugging python code via pytest has just stopped working.</p> <p>My previous process was as follows:</p> <ol> <li>Insert the debugpy macro either above the pytest test definition or at the top level of the code being debugged.</li> </ol> <pre><code>import debugpy deb...
<python><visual-studio-code><vagrant><vscode-debugger>
2023-01-10 18:28:36
3
510
smallpants
75,074,306
9,661,008
How to remove repeated sentences from a string
<p>I have an issue that I do not know how to tackle.</p> <p>For example: I have a string returning in a function that has multiple sentences separatade by a comma. And some of them are comming repeated:</p> <p>Like:</p> <p><code>&quot;lorem ipsum dolor, lorem ipsum dolor, lorem ipsum dolor&quot;</code></p> <p>I need to...
<python>
2023-01-10 18:25:28
3
1,874
Elias Prado
75,074,045
5,805,389
Typehinting async function and passing to asyncio.create_task
<p>In my research, I see the general consensus for the correct way to typehint an async function is <code>Callable[..., Awaitable[Any]]</code>.</p> <p>In Pycharm, I try this and have this issue when passing to <code>asyncio.create_task</code></p> <pre class="lang-py prettyprint-override"><code>import asyncio from typin...
<python><pycharm><type-hinting>
2023-01-10 17:59:49
1
805
Shuri2060
75,074,036
14,551,577
How to download pdf from html embed tag without src rendered by javascript in python selenium
<p>I am going to download pdf from html page.</p> <p>The page structure is following.</p> <p><code>index.html</code>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe src=&quot;a.html&quot;&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code...
<python><selenium><pdf><web-scraping><download>
2023-01-10 17:59:08
0
644
bcExpt1123
75,074,008
16,978,074
OSError: [Errno 28] No space left on device when I run a python program
<p>Hello all when I run a python program that makes network requests and downloads a lot of data, I get this error:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Python311\Lib\site-packages\pandas\io\formats\csvs.py&quot;, line 261, in save self._save() File &quot;C:\Python311\Lib\site-package...
<python><oserror>
2023-01-10 17:56:12
0
337
Elly
75,073,999
18,403,743
Using Aspose.Slides For Python With MacOS
<p>I'm utilising aspose.slides for Python successfully on Windows, recently they've added MacOS support. When I try to run ANY aspose.slides script on MacOS I get an error that it can't find libpython dylib in /usr/lib or /usr/local/lib</p> <p>Simple example</p> <pre><code>import aspose.slides as slides # Instantiate ...
<python><aspose><aspose-slides>
2023-01-10 17:55:05
0
372
Luke Bowes
75,073,830
10,530,575
Python - run script at every specific MINUTE time of the day
<p>I need to run a python script at specific time at EVERY minutes. I CANNOT use time.sleep to wait 60 second for it, because my script takes 8-10 seconds to run, (60 + 8 = 68 or 60+10 = 70οΌ‰ I need to run the script at below specific time through out the day.</p> <pre><code>2023-01-09 01:01:05 2023-01-09 01:02:05 2023-...
<python><python-3.x><dataframe><datetime>
2023-01-10 17:38:29
1
631
PyBoss
75,073,788
12,506,486
Pyspark - withColumn + when with variable give "Method or([class java.lang.Boolean]) does not exist"
<p>I need to add a column to data frame based on the one of the other columns AND a variable value (represented here as <code>otherThing</code>), see below:</p> <pre class="lang-py prettyprint-override"><code>otherThing = &quot;test&quot; dataDF = spark.createDataFrame([(66, &quot;a&quot;, &quot;4&quot;), ...
<python><dataframe><pyspark>
2023-01-10 17:34:15
1
1,734
Stachu
75,073,786
16,484,106
How do I write to a Python subprocess?
<p>I'm trying to write a Python script that starts a subprocess to run an Azure CLI command once the file is executed.</p> <p>When I run locally, I run:</p> <pre><code>az pipelines create --name pipeline-from-cli --repository https://github.com/&lt;org&gt;/&lt;project&gt; --yml-path &lt;path to pipeline&gt;.yaml --fold...
<python><python-3.x><azure-devops><subprocess><azure-cli>
2023-01-10 17:34:10
2
384
agw2021
75,073,719
62,206
Python object returning different property values between threads
<h2>Problem</h2> <p>I'm experiencing unexpected behavior when trying to update an objects properties across threads. During application start, I spawn a thread to do some I/O that I don't want to block the main thread starting up the rest of the application. I then want to communicate back to the main thread that we h...
<python><multithreading><concurrency>
2023-01-10 17:28:26
1
1,199
Zack
75,073,594
13,054,038
Access python global variable inside airflow task group
<p>I have set the variable <code>cluster_key</code> in a python function which is called via a python operator.</p> <pre><code>cluster_key = &quot;&quot; new_key =&quot;&quot; def dynamic_list(e_run_id): global cluster_key cluster_key = 'key_cluster_'+e_run_id+'' global new_key new_key = 'new_key_'+e_r...
<python><python-3.x><airflow>
2023-01-10 17:16:35
1
313
djgcp
75,073,590
3,896,008
How to remove boundaries in matplotlib rectangles?
<p>The following snippet draws non-overlapping rectangles and works as expected:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, aspect=1) for i in range(5, 30, 5): for j in range(5, 30, 5): rect = m...
<python><matplotlib>
2023-01-10 17:16:16
1
1,347
lifezbeautiful
75,073,571
468,455
How to add a Google formula containing commas and quotes to a CSV file?
<p>I'm trying to output a CSV file from Python and make one of the entries a Google sheet formula:</p> <p>This is what the formula var would look like:</p> <pre><code> strLink = &quot;https://xxxxxxx.xxxxxx.com/Interact/Pages/Content/Document.aspx?id=&quot; + strId + &quot;&amp;SearchId=0&amp;utm_source=interact&amp...
<python><csv><google-sheets><formula>
2023-01-10 17:14:27
2
6,396
PruitIgoe
75,073,480
3,624,171
Pandas ValueError: Columns must be same length as key PyCharm
<p>I want to use a dictionary to add a column to a pandas DataFrame. I use apply lambda with a function to a row. I get 'ValueError: Columns must be same length as key'. I should be able to add a new column, but to simplify I included the column to change in the df.</p> <p>I don't see what I'm doing wrong.</p> <pre><c...
<python><python-3.x><pandas><dataframe>
2023-01-10 17:07:19
3
432
Steve Maguire
75,073,470
10,710,625
sum rows from two different data frames based on the value of columns
<p>I have two data frames</p> <p><code>df1</code></p> <pre><code> ID Year Primary_Location Secondary_Location Sales 0 11 2023 NewYork Chicago 100 1 11 2023 Lyon Chicago,Paris 200 2 11 2023 Berlin Paris 300...
<python><pandas><dataframe>
2023-01-10 17:06:49
2
739
the phoenix
75,073,409
25,282
Python: Download Google Doc as Odt
<p>I want to download a Google doc as an <code>.odt</code>-file. There's a <a href="https://stackoverflow.com/q/38511444/25282">previous question</a> on how to download normal files from Google Drive.</p> <p>I want to download the Doc with Python, because I then want to continue to work with it within my slave.</p>
<python><google-docs><google-docs-api>
2023-01-10 17:01:16
1
26,469
Christian
75,073,367
1,245,420
How to call SCons global function from a helper-script called by a SConscript?
<p>I have some non-trivial logic necessary to compute the paths to certain source &amp; header file directories and since it applies to multiple SConscripts I put it in a separate .py file, imported from each SConscript that needs it. Now I need to be able to call a SCons global function (in this case, the <code>Glob</...
<python><scons>
2023-01-10 16:56:14
1
7,893
phonetagger
75,073,085
19,826,650
Passing array object from PHP to Python
<p>This is my code so far</p> <pre><code> $dataraw = $_SESSION['image']; $datagambar = json_encode($dataraw); echo '&lt;pre&gt;'; print_r($dataraw); echo '&lt;/pre&gt;'; print($escaped_json); $type1 = gettype($dataraw); print($type1); $type2 = gettype($datagambar); print($type...
<python><php><json>
2023-01-10 16:34:05
2
377
Jessen Jie
75,072,979
4,736,140
Python Export table from postgres and import to another postgres using
<p>I have 2 postgres databases with same schema but in 2 different schemas. I am writing a python script with a goal to export data partially from one of the tables and import the result to the same table but in a different database (like <code>select from A where f=123</code>). The schema is large (it has many columns...
<python><database><postgresql>
2023-01-10 16:25:52
1
2,277
komron
75,072,886
9,343,043
Create all possible combinations of entries from multiple lists
<p>I have different scalar metrics that I need to take inventory of in a large repository of data. The format of one entry for a metric would look something like this:</p> <pre><code>{a}_{b}_{c}_{d} # Where ${a} = subjid, ex. &quot;1000061&quot; # Where ${b} = &quot;ROIstats&quot; # ...
<python><string><list><combinations><python-itertools>
2023-01-10 16:19:02
0
871
florence-y
75,072,848
4,817,370
Python : how can I know which one of my dependencies is attempting to install a specific package?
<p>I have a project with a requirements.txt file that is quite big ( 67 dependencies ). One of the dependencies is attempting to use the psycopg2 package installed and fails. I would prefer to install the psycopg2-binary package</p> <p>How can I find witch one of the dependencies requires psycopg2 ?</p> <p>I have attem...
<python><python-3.x><pip>
2023-01-10 16:16:27
2
2,559
Matthieu Raynaud de Fitte
75,072,821
11,781,149
Comparing the value of a column with the previous value of a new column using Apply in Python (Pandas)
<p>I have a dataframe with these values in column A:</p> <pre><code>df = pd.DataFrame(A,columns =['A']) A 0 0 1 5 2 1 3 7 4 0 5 2 6 1 7 3 8 0 </code></pre> <p>I need to create a new column (called B) and populate it using next conditions:</p> <p>Condition 1: If the value of A is equal to 0 then, ...
<python><pandas><dataframe><apply>
2023-01-10 16:14:02
4
523
Martingale
75,072,815
10,873,155
Python can't locate module files from other directory
<p>I have a project structured as follow:</p> <pre><code>project\ __init__.py gui\ __init__.py gui_file_one.py gui_file_two.py logic\ __init__.py logic_file_one.py logic_file_two.py </code></pre> <p>Let's say that in a <code>gui_file_one.py</code> I need to import class A th...
<python>
2023-01-10 16:13:42
0
326
Jakub Sapko
75,072,671
15,399,131
Invalid python interpreter when using virtualenv --system-site-packages in VSCode
<p>Ideally I would like to use <a href="https://stackoverflow.com/questions/71484282/loading-an-lmod-module-using-vscode-with-remote-ssh">Loading an Lmod module using VSCode with Remote-SSH</a> however the soultion to use that directly does not seem to work. On the other hand virtualenvs ought to be <a href="https://co...
<python><virtualenv><vscode-remote>
2023-01-10 16:03:47
0
642
VRehnberg
75,072,650
12,258,312
Finding mentioned weekdays from text
<p>Let's say we have a text of</p> <blockquote> <p>Even though we celebrate Good Friday and Easter Sunday, there is no mention of days such as &quot;Sunday&quot; or &quot;Wednesday&quot;.</p> </blockquote> <p>Notice the following weekdays are mentioned, <code>Friday, Sunday, Sunday, Wednesday</code></p> <p>We need outp...
<python>
2023-01-10 16:01:52
2
1,204
Tim Abdiukov
75,072,627
3,986,055
Python: create a file on S3
<p>I have a function below for generating the rows of a huge text file.</p> <pre class="lang-py prettyprint-override"><code>def generate_content(n): for _ in range(n): yield 'xxx' </code></pre> <p>Instead of saving the file to disk, then uploading it to S3, is there any way to save the data directly to S3?<...
<python><amazon-web-services><file><amazon-s3><upload>
2023-01-10 15:59:58
1
1,484
Ken Zhang
75,072,597
3,715,862
"Required Content-Range response header is missing or malformed" while using download_blob in azure blob storage using cdn hostname
<p>I have a storage account in azure with a connection string in the format :</p> <pre><code>connection_string = 'DefaultEndpointsProtocol=https;AccountName=&lt;storage_account_name&gt;;AccountKey=&lt;redacted_account_key&gt;;EndpointSuffix=azureedge.net' </code></pre> <p>I am trying to download a blob from a container...
<python><azure><azure-blob-storage><azure-cdn>
2023-01-10 15:57:43
1
600
Echo
75,072,498
10,647,708
Removing all text within double quotes
<p>I am working on preprocessing some text in Python and would like to get rid of all text that appears in double quotes within the text. I am unsure how to do that and will appreciate your help with. A minimally reproducible example is below for your reference. Thank you in advance.</p> <pre><code>x='The frog said &qu...
<python><python-3.x>
2023-01-10 15:50:53
2
329
Dave
75,072,472
6,694,814
Python folium fetching csv data to the jinja macro template
<p>I have the jinja macro template provided to my code, which executes the Leaflet circle creation.</p> <p>I would like to include the .csv data in this template when possible</p> <pre><code>df = pd.read_csv(&quot;survey.csv&quot;) class Circle(folium.ClickForMarker): _template = Template(u&quot;&quot;&quot; {...
<javascript><python><leaflet><folium>
2023-01-10 15:49:05
0
1,556
Geographos
75,072,374
10,647,708
Removing these trailing characters from text in Python
<p>I am working with text in Python and trying to remove trailing characters. I am aware of the <code>rstrip</code> function but it unfortunately does not get rid of the trailing characters due (I think) to the nature of the trailing characters. Below is a minimally reproducible example I would appreciate your help wit...
<python><python-3.x>
2023-01-10 15:42:24
1
329
Dave
75,072,265
16,511,234
Time series resample seems to result in wrong data
<p>I have data with 30 minutes interval. When I resample it to 1 hour I get kind of low values.</p> <p>Original data:</p> <pre><code>2022-12-31 22:00:00+01:00;7.500000 2022-12-31 22:30:00+01:00;8.200000 2022-12-31 23:00:00+01:00;10.800000 2022-12-31 23:30:00+01:00;9.500000 2023-01-01 00:00:00+01:00;12.300000 2023-01-01...
<python><pandas><date><datetime>
2023-01-10 15:33:42
1
351
Gobrel
75,072,264
4,542,117
How to ignore specific numbers in a numpy moving average?
<p>Let's say I have a simple numpy array:</p> <pre><code>a = np.array([1,2,3,4,5,6,7]) </code></pre> <p>I can calculate the moving average of a window with size 3 simply like:</p> <pre><code>np.convolve(a,np.ones(3),'valid') / 3 </code></pre> <p>which would yield</p> <pre><code>array([2., 3., 4., 5., 6.]) </code></pre>...
<python><numpy>
2023-01-10 15:33:36
1
374
Miss_Orchid
75,072,229
245,549
How to use hash function in Python3 to transform an arbitrary string into a fixed-length sequence of alphanumeric symbols?
<p>I have a large number of different sentences written in different languages (French, Ukrainian, English and so on). For each sentence I want to generate audio file with the given sentence being pronounced by a text-to-speech program. Now I need to decide how to name those audio files (one file for each sentence). I ...
<python><hash>
2023-01-10 15:31:00
1
132,218
Roman
75,072,207
357,313
Why does read_csv give me a timezone warning?
<p>I try reading a CSV file using pandas and get a warning I do not understand:</p> <pre><code>Lib\site-packages\dateutil\parser\_parser.py:1207: UnknownTimezoneWarning: tzname B identified but not understood. Pass `tzinfos` argument in order to correctly return a timezone-aware datetime. In a future version, this wi...
<python><pandas><datetime><timezone><python-dateutil>
2023-01-10 15:29:06
1
8,135
Michel de Ruiter
75,072,007
1,382,437
Python/Jupyter: scroll scatter-plot with many data points horizontally
<p>I want to visualize time-series-like data with several measurements over time.</p> <p>There are a lot of such measurements in a dataset, in the order of tens to hundreds of thousands.</p> <p>In order to view these in a notebook or HTML page, I would like some efficient method to show a subrange of the whole time ran...
<python><python-3.x><plotly><scatter-plot><line-plot>
2023-01-10 15:13:45
1
2,137
jpp1
75,071,918
10,687,615
Count number of " date hour minutes" before two datetime points
<p>I have code that will give me the cumulative number of patients in a location by hour between two date/time points. However, I want to tweak this code to show the data by minutes.</p> <pre><code>Datatable: ID ARRIVAL_DATE_TIME DISPOSITION_DATE 1 2021-11-07 08:35:00 2021-11-07 17:58:0...
<python><pandas>
2023-01-10 15:05:40
1
859
Raven
75,071,688
17,696,880
Set if conditional inside a lambda function depending on whether a value captured using regex is None or ""
<pre class="lang-py prettyprint-override"><code>import re input_text = 'desde el 2022_-_12_-_10 corrimos juntas hasta el 11Β° nivel de aquella montaΓ±a hasta el 2022_-_12_-_13' #example 1 #input_text = 'desde el 2022_-_11_-_10 18:30 pm hasta el 2022_-_12_-_01 21:00 hs' #example 2 #text in the middle associated with the...
<python><python-3.x><regex><lambda><regex-group>
2023-01-10 14:49:03
1
875
Matt095