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,123,191
132,042
Pandas' Series.plot() stacks disjoint segments instead of adjoining them
<p>I'm following the video from <a href="https://www.coursera.org/learn/python-statistics-financial-analysis/lecture/mfHGK/1-3-basics-of-dataframe" rel="nofollow noreferrer">2018 or 2019 on Coursera</a> that explains the basics of how to use <code>pandas</code>. The examples are based on the Facebook stock data that on...
<python><pandas><windows><anaconda>
2023-01-15 05:49:55
2
1,313
Tatiana Racheva
75,122,995
1,146,785
can I run a shell task in VSCode that uses a specific shell for a python virtualEnv?
<p>I'm writing some python to render stuff that I tweak and run a lot, and that runs inside a virtual env. I would like a keyboard command to run a bash script (that launches python) inside the known terminal and virtual env.</p> <p>I played a bit with setting up a shell script and a custom task, but entering the virtu...
<python><visual-studio-code><virtualenv>
2023-01-15 04:47:23
2
12,455
dcsan
75,122,991
10,411,973
Python ping by reading txt file contain list of IP address and string or name next to it
<p>I'm testing running simple script to ping few servers by calling a text file iplist.txt. The script working if txt file only contain IP address. Now I'm adding hostname next to the IP address in the iplist.txt and ping failed.</p> <pre><code>Original only IP address in iplist.txt 192.168.1.1 192.168.1.2 Updated w...
<python><ping><txt>
2023-01-15 04:46:36
1
565
chenoi
75,122,916
1,436,800
How to make customize detail view set using ModelViewSet?
<p>I am new to django. I have a model:</p> <pre><code>class Class(models.Model): name = models.CharField(max_length=128) students = models.ManyToManyField(&quot;Student&quot;) def __str__(self) -&gt; str: return self.name </code></pre> <p>Now I want to create API to display the students in a parti...
<python><django><django-models><django-rest-framework><django-views>
2023-01-15 04:24:45
1
315
Waleed Farrukh
75,122,915
2,446,702
Python Pandas - how to write a string to a spcific cell via index without using the dataframe
<p>I am trying to use pandas to write a value to a specific cell via index (1,1), in an xlsx file. Lets say I currently have an xlsx file:</p> <pre><code>A B C 1 2 3 </code></pre> <p>How can I update 2 to another value without using the whole dataframe please? For the pupose of what I working on, I would li...
<python><python-3.x><pandas><xlsx>
2023-01-15 04:24:36
1
3,255
speedyrazor
75,122,794
12,224,591
Provide Specific Face Colors to trisurf? (MatPlotLib, PY 3.10)
<p>I'm attempting to find a way to provide different colors to the <code>trisurf</code> function, called on a <code>scatter</code> plot, in <code>Python 3.10</code> using the <code>MatPlotLib</code> module.</p> <p>Let's say I have the following simple plot script:</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(...
<python><matplotlib>
2023-01-15 03:42:44
1
705
Runsva
75,122,712
422,348
How can I run a simple twisted client on top of asyncio?
<p>I have the following client code that I borrowed from twisted's docs:</p> <p><a href="https://docs.twistedmatrix.com/en/twisted-20.3.0/web/howto/client.html#the-agent" rel="nofollow noreferrer">https://docs.twistedmatrix.com/en/twisted-20.3.0/web/howto/client.html#the-agent</a></p> <p>And I am trying to run it with ...
<python><python-asyncio><twisted><twisted.internet><twisted.client>
2023-01-15 03:16:50
1
2,482
Ruben Quinones
75,122,563
5,924,264
Assigning one column of dataframe to column of another dataframe with disparate indices?
<p>I have dataframes <code>first</code> and <code>second</code> of the same length, where the first one's index is increments of 15 and the second is in increments of 1. I would like to assign one column of <code>first</code> to another of <code>second</code>.</p> <p>e.g., something like below</p> <pre><code>import pan...
<python><pandas><dataframe>
2023-01-15 02:24:10
1
2,502
roulette01
75,122,558
1,348,878
How to Import Integer as Numeric String and not in Scientific Notation
<p>Trying to import a JSON file which is list of dictionaries, one of which contains two epoch time values (start time and end time). Now, if all instances include both times, no problem--pandas json.normalize will load all values correctly as they appear in the source data. But because some end-time values are missing...
<python><json><pandas>
2023-01-15 02:22:21
1
517
Kirk Fleming
75,122,503
3,591,044
Remove number patterns from string
<p>I have conversations that look as follows:</p> <pre><code>s = &quot;1) Person Alpha:\nHello, how are you doing?\n\n1) Human:\nGreat, thank you.\n\n2) Person Alpha:\nHow is the weather?\n\n2) Human:\nThe weather is good.&quot; 1) Person Alpha: Hello, how are you doing? 1) Human: Great, thank you. 2) Person Alpha: ...
<python><python-3.x><string><replace>
2023-01-15 02:04:30
5
891
BlackHawk
75,122,487
4,155,976
Graphviz running on SageMaker notebook instance but not SageMaker Studio
<p>I'm running a python script with PyTorch/Graphviz. It executes in a SageMaker notebook instance, but not in SageMaker Studio.</p> <p>It appears the notebook instance with kernel <strong>conda_pytorch_p39</strong> already contains an installation of Graphviz so the script just works as is and I get my Graphviz png.</...
<python><pytorch><graphviz><amazon-sagemaker><amazon-sagemaker-studio>
2023-01-15 01:59:04
1
12,017
Edison
75,122,437
19,094,667
Finding all positions of an object in an image
<p>My goal is to find the locations of specific image on other PNG image, using python. Take this example:</p> <p><a href="https://i.sstatic.net/LctMn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LctMn.png" alt="subimage" /></a></p> <p><a href="https://i.sstatic.net/BkuDj.png" rel="nofollow noreferrer...
<python><python-imaging-library>
2023-01-15 01:40:06
1
517
Agan
75,122,111
17,696,880
Set regex pattern that concatenates one capture group or another depending on whether or not the input string starts with certain symbols
<pre class="lang-py prettyprint-override"><code>import re word = &quot;&quot; input_text = &quot;Creo que July no se trata de un nombre&quot; #example 1, should match with the Case 00 #input_text = &quot;Creo que July Moore no se trata de un nombre&quot; #example 2, should not match any case #input_text = &quot;Efecti...
<python><python-3.x><regex><string><regex-group>
2023-01-15 00:03:56
1
875
Matt095
75,121,925
706,389
Why doesn't python logging.exception method log traceback by default?
<p>When writing defensive code in python (e.g. you're handling some user input or whatever), I find it useful to return <code>Exception</code> objects alongside regular computation results, so they can be discarded/logged or processed in some other way. Consider the following snippet:</p> <pre class="lang-py prettyprin...
<python><exception><python-logging>
2023-01-14 23:18:03
2
2,549
karlicoss
75,121,856
580,644
Beautifulsoup add attribute to first <td> item in a table
<p>I would like to get a table html code from a website with Beautifulsoup and I need to add attribute to the first td item. I have:</p> <pre><code>try: description=hun.select('#description &gt; div.tab-pane-body &gt; div &gt; div &gt; div &gt; table')[0] description+=&quot;&lt;style type=text/css&gt;td...
<python><beautifulsoup>
2023-01-14 23:03:45
1
2,656
Adrian
75,121,814
222,977
How to deal with NumPy array product underflow and overflow
<p>I have 2d numpy array of shape (15077, 5). All the values are less than or equal to 1.0. I'm essentially trying to do the following:</p> <pre class="lang-py prettyprint-override"><code>product = array.prod(axis=0) product = product / product.sum() </code></pre> <p>So basically I want to return an array that represen...
<python><python-3.x><numpy><numpy-ndarray>
2023-01-14 22:56:29
1
583
Dan
75,121,807
3,672,883
what are keypoints in yolov7 pose?
<p>I am trying to understad the keypoint output of the yolov7, but I didn't find enough information about that.</p> <p>I have the following output:</p> <pre><code>array([ 0, 0, 430.44, 476.19, 243.75, 840, 0.94348, 402.75, 128.5, 0.99902, 417.5, 11...
<python><pytorch><yolo><yolov7>
2023-01-14 22:54:25
1
5,342
Tlaloc-ES
75,121,793
9,855,588
how would you import a variable from a library when you have a utility that references the variable python
<p>Say I am using library XYZ that stores a variable in <strong>init</strong>.py.</p> <p>I have the following files:</p> <pre><code>some_library/__init__.py hello=&quot;frog&quot; file1.py import some_library def run(): print(some_library.hello) file2.py (at this point I can access hello from some_library/__init...
<python><python-3.x>
2023-01-14 22:51:17
0
3,221
dataviews
75,121,671
12,603,542
Calling open() with 'append' mode throws: [Errno 2] No such file or directory exception in Python
<p>It is kind of weard situation and I can not find similar problem anywhere. In my situation we call 'open' with 'append' parameter, as below.</p> <p>I am using a function that calls other mehod:</p> <pre><code>fileManager.saveNewLine(result_line, results_path, &quot;a&quot;) #below is fileManager def saveNewLine(tex...
<python><file><io>
2023-01-14 22:25:58
1
631
bakunet
75,121,419
19,003,861
Django - Annotate within for loop - what is the difference between my two codes
<p>I am trying to sum up two columns in a view with <code>values()</code> and <code>annotate()</code>.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column 1</th> <th>Column 2</th> </tr> </thead> <tbody> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>5</td> <td>-2</td> </tr> </tbody> </table> ...
<python><django><django-views>
2023-01-14 21:36:43
1
415
PhilM
75,121,353
19,678,835
Automate AWS ECR scanning
<p>I have tried to automate ECR image scanning using AWS CLI. But I was stuck in the scanning step. When I call <code>aws ecr start-image-scan</code>, it starts the scanning. But how I know the scanning is finish. My images are large and it takes few minutes. Could someone help me to figure out this. I am using Python<...
<python><amazon-ecr><scanning>
2023-01-14 21:24:32
2
488
Mark P
75,121,352
10,772,422
StableBaselines creating a model segmentation fault
<p>I am getting a segmentation fault when trying to create a stable_baselines3 PPO model on a CartPole-v1 OpenAI Gym environment.</p> <p>So far what I've tried is running a short example code on Python 3.10 as well as Python 3.9. I'm running the python script in a Conda environment. What I did was install stable-baseli...
<python><segmentation-fault><openai-gym><stable-baselines>
2023-01-14 21:24:21
1
361
Ilija Vuk
75,121,336
252,226
Cannot start dask client
<p>When I try and initiate a dask distributed cluster with:</p> <pre><code>from dask.distributed import Client, progress client = Client(threads_per_worker=1, n_workers=2) client </code></pre> <p>I get the following error:</p> <p><code>RuntimeError: Cluster failed to start: module 'numpy' has no attribute 'bool8'</code...
<python><numpy><dask><dask-distributed>
2023-01-14 21:22:05
0
783
dbschwartz
75,121,204
17,561,414
JSON items data types python
<p>I have the following JSON structure.</p> <p><a href="https://i.sstatic.net/Lc5KV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Lc5KV.png" alt="enter image description here" /></a></p> <p>Goal is to identify datatypes of each nested keys under <code>items</code> hierarchy.</p> <pre><code>for i, item ...
<python><json><dictionary><flatten>
2023-01-14 21:01:30
0
735
Greencolor
75,121,127
2,584,721
Save all intermediate variables in a function, should the function fail
<p>I find myself frequently running into this sort of problem. I have a function like</p> <pre class="lang-py prettyprint-override"><code>def compute(input): result = two_hour_computation(input) result = post_processing(result) return result </code></pre> <p>and <code>post_processing(result)</code> fails. N...
<python><python-decorators>
2023-01-14 20:47:22
7
14,710
Alex Lenail
75,121,034
11,462,274
Create a lambda function to set values in a column without being alerted for value set in a copy of a slice of a DataFrame
<p>Object <code>archive</code>:</p> <pre class="lang-none prettyprint-override"><code>match_date,start_time,competition,team_home,team_away,match,tip,reliability,odds,home_goals,away_goals,score,result 2023-01-13,16:45,Italian Serie A,Napoli,Juventus,Napoli v Juventus,Under 2.5 Goals,3,1.8,, 2023-01-13,17:00,English Pr...
<python><pandas><dataframe>
2023-01-14 20:31:11
1
2,222
Digital Farmer
75,121,012
997,832
Tensorflow model with multuple inputs
<p>I have the following neural net model. I have an input to as int sequence. And there is also another two neural nets beginning from same type of input layer and get concatenated together. This concatenation is the final output of the model. If I specified the input of the model as <code>main_input</code> and the <co...
<python><tensorflow><deep-learning>
2023-01-14 20:25:04
1
1,395
cuneyttyler
75,120,918
11,462,274
When trying to use update to combine two DataFrame, the result is None
<p>Object <code>archive</code>:</p> <pre class="lang-none prettyprint-override"><code>match_date,start_time,competition,team_home,team_away,match,tip,reliability,odds,home_goals,away_goals,score,result 2023-01-13,16:45,Italian Serie A,Napoli,Juventus,Napoli v Juventus,Under 2.5 Goals,3,1.8,, 2023-01-13,17:00,English Pr...
<python><pandas><dataframe>
2023-01-14 20:07:43
1
2,222
Digital Farmer
75,120,795
15,724,084
python scrapy different result when running from shell when as script
<p><a href="https://i.sstatic.net/y4Z9K.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/y4Z9K.png" alt="enter image description here" /></a>I have my script when I run script my print statement gives 'None' value. But when the same thing is run from scrapy shell I can get result what i want; What can be ...
<python><scrapy>
2023-01-14 19:49:14
1
741
xlmaster
75,120,783
9,256,321
Sum of a sequence in Python
<p>Let me present my problem in mathematical notation before diving into the programming aspect.</p> <p>Let <code>a_n</code> be the sequence whose <code>i</code>th term is defined as <code>i^2 - (i-1)^2</code>. It is easy to see <code>a_i = 2i-1</code>. Hence (in mathematical notation) we have <code>a_n = {2-1, 4-1, .....
<python><math><lambda>
2023-01-14 19:47:27
1
350
lafinur
75,120,551
1,459,607
Python hashlib is giving different results
<p>For some reason, my code below is giving inconsistent results. The files in <code>files</code> do not ever change. However, the result of <code>hasher.hexdigest()</code> is giving different values each time this function runs. My goal with this code is to only generate a new settings file if and only if the checksum...
<python><md5><hashlib>
2023-01-14 19:03:36
1
1,386
Ryan Glenn
75,120,494
8,584,998
Torpy Stream #4: closed already; Connection broken: IncompleteRead(634 bytes read, 3974 more expected)
<p>I am trying to use torpy to query Bitcoin balances over tor.</p> <pre><code>from torpy.http.requests import TorRequests import json addr1 = r'34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo' addr2 = r'bc1qgdjqv0av3q56jvd82tkdjpy7gdp9ut8tlqmgrpmv24sq90ecnvqqjwvw97' with TorRequests() as tor_requests: print(&quot;establish cir...
<python><blockchain><bitcoin><tor>
2023-01-14 18:53:33
1
1,310
EllipticalInitial
75,120,329
3,247,006
Doesn't "__str__()" work properly in "admin.py" for Django Admin?
<p>For example, I define <a href="https://docs.djangoproject.com/en/4.1/ref/models/instances/#str" rel="nofollow noreferrer">__str__()</a> in <strong><code>Person</code> model</strong> as shown below:</p> <pre class="lang-py prettyprint-override"><code># &quot;models.py&quot; from django.db import models class Person...
<python><django><function><django-admin><django-messages>
2023-01-14 18:26:33
1
42,516
Super Kai - Kazuya Ito
75,120,244
580,644
Beautifulsoup remove bracket from output
<p>I am trying to get html from a web page:</p> <pre><code>try: description=hun.select('#description &gt; div.tab-pane-body &gt; div &gt; div &gt; div &gt; table') except: description=None result = {&quot;description&quot;:str(description)} data.append(result) print(json2xml.Json2xml(data, wrapper=&quot;all&...
<python><python-3.x><beautifulsoup>
2023-01-14 18:14:49
2
2,656
Adrian
75,120,176
5,947,182
How do you move mouse with Playwright Python?
<p>I'm writing a test code to <strong>check if the mouse is moving in the Playwright browser</strong>. I used <code>pyautogui</code> in this case to locate current mouse position but that might be the problem, so I was wondering if there is a similar method for Playwright Python?</p> <p>Please have a look at the code b...
<python><mouse><playwright>
2023-01-14 18:04:12
1
388
Andrea
75,120,076
6,534,818
Practically implementing CTCLoss
<p>This thread covers some of the nuances about CTC Loss and its unique way of capturing repeated characters and blanks in a sequence: <a href="https://stackoverflow.com/questions/55284586/ctc-what-is-the-difference-between-space-and-blank">CTC: What is the difference between space and blank?</a> but its practical impl...
<python><tensorflow><machine-learning><pytorch><computer-vision>
2023-01-14 17:47:37
1
1,859
John Stud
75,120,012
11,462,274
Replace values in specific rows from one DataFrame to another when certain columns have the same values
<p>Unlike the other questions, I don't want to create a new column with the new values, I want to use the same column just changing the old values for new ones if they exist.</p> <p>For a new column I would have:</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd df1 = pd.DataFrame(data = {'Na...
<python><pandas><dataframe>
2023-01-14 17:39:39
2
2,222
Digital Farmer
75,119,883
17,561,414
Json flattening python
<p>My goal is to identify which instanse is <code>dict</code>, <code>str</code> or <code>list</code> under the <code>items</code> hierarchy.</p> <pre><code>def flatten(data): for i, item in enumerate(data['_embedded']['items']): if isinstance(item, dict): print('Item', i, 'is a dict') el...
<python><json><flatten><json-flattener>
2023-01-14 17:21:28
1
735
Greencolor
75,119,644
7,197,067
Synth of AWS gateway load balancer in python CDK is failing
<p>I am trying to create an AWS Gateway Load Balancer configuration in AWS CDK (python). I already have a working version in Cloud Formation. The synth step is failing, seemingly, because CDK is not recognizing a &quot;list&quot; as a Sequence.</p> <p>Below is the key bit of python. Note that I'm using L1 constructs si...
<python><amazon-web-services><aws-cdk><amazon-elb><gateway>
2023-01-14 16:50:20
1
314
Pat
75,119,478
13,359,498
ValueError: Dimensions must be equal, but are 4 and 224 for '{{node Equal}} = Equal[T=DT_FLOAT, incompatible_shape_error=true]
<p>I am trying o build a neural network, but I am facing problems fitting that.</p> <p>Data shapes:</p> <p>X_train = (555, 224, 224, 3)</p> <p>X_test = (99, 224, 224, 3)</p> <p>y_train = (555, 4)</p> <p>y_test = (99, 4)</p> <p>X_val = (116, 224, 224, 3)</p> <p>y_val = (116, 4)</p> <p>Code snippet:</p> <pre><code>from k...
<python><tensorflow><keras><deep-learning><neural-network>
2023-01-14 16:30:02
0
578
Rezuana Haque
75,119,381
9,974,205
Problem Following Web Scraping Tutorial Using Python
<p>I am following this <a href="https://www.makeuseof.com/python-scrape-web-images-how-to/#python-package-set-up" rel="nofollow noreferrer">web scraping tutorial</a> and I am getting an error.</p> <p>My code is as follows:</p> <pre><code>import requests URL = &quot;http://books.toscrape.com/&quot; # Replace this with t...
<python><image><web-scraping><url><beautifulsoup>
2023-01-14 16:17:51
1
503
slow_learner
75,119,303
10,924,836
Plotting density chart
<p>I am trying to plot a density chart. Below you can see data and chart</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt data = {'type_sale':[100,200,400,400,200,400,300,200,210,300], 'bool':[0,1,0,1,1,0,1,1,0,1], } df1 = pd.DataFrame(data, columns = ['type_sale', ...
<python><matplotlib>
2023-01-14 16:05:26
1
2,538
silent_hunter
75,119,153
10,829,044
pandas transform n columns to n/3 columns and n/3 rows
<p>I have a dataframe like as shown below</p> <pre><code>data = { 'key':['k1','k2'], 'name_M1':['name', 'name'],'area_M1':[1,2],'length_M1':[11,21],'breadth_M1':[12,22], 'name_M2':['name', 'name'],'area_M2':[1,2],'length_M2':[11,21],'breadth_M2':[12,22], 'name_M3':['name', 'name'],'area_...
<python><pandas><dataframe><pivot><transformation>
2023-01-14 15:44:55
1
7,793
The Great
75,119,141
19,009,577
Get list of tuples of stacked for loop values
<p>While trying to speed up:</p> <pre><code>l = some_value for i in range(1000): for j in range(1000): for k in range(1000): function(i, j, k, l) </code></pre> <p>I stumbled upon <code>multiprocessing.Pool().starmap()</code> however it requires the iterated values to be passed in as an interator...
<python><for-loop><multiprocessing><python-multiprocessing>
2023-01-14 15:43:17
1
397
TheRavenSpectre
75,119,070
1,849,163
How to get the last date of the current week or quarter in python?
<p>I would like to find a simple way to get the last date of the current week or quarter.</p> <p>To get the last date of the current month I can use the <code>relativdelta</code> function from <code>dateutil</code>:</p> <pre><code>import pandas as pd today_date = pd.Timestamp.today().date() #get today's date from dat...
<python><python-datetime>
2023-01-14 15:30:38
1
351
econlearner
75,119,036
275,002
How to export loads of MysQL record in CSV in chunks in Python?
<p>TO clarify, I am on a shared hosting so <code>mysqldump</code> and <code>OUTFILE</code> is not available for me, at least on NameCheap hosting. I am using the following code</p> <pre><code>def fetch(connection, id_count, offset): records = None try: if connection is not None: with connect...
<python><namecheap>
2023-01-14 15:24:18
1
15,089
Volatil3
75,118,894
20,266,647
Issue with dynamic allocation in PySpark session (under MLRun and in K8s)
<p>I would like to maximize power of Spark cluster in MLRun solution for my calculation and I used this session setting for Spark cluster in MLRun solution (it is under Kubernetes cluster):</p> <pre><code>spark = SparkSession.builder.appName('Test-Spark') \ .config(&quot;spark.dynamicAllocation.enabled&quot;, True)...
<python><apache-spark><kubernetes><dynamic-memory-allocation><mlrun>
2023-01-14 15:03:46
1
1,390
JIST
75,118,729
17,160,160
Python. DFS graph traversal, correct output?
<p>I'm currently getting to grips with graph traversal in Python.</p> <p>Given the following graph:</p> <p><a href="https://i.sstatic.net/aCStw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aCStw.png" alt="enter image description here" /></a></p> <p>Implemented using this dictionary:</p> <pre><code> gr...
<python><graph-theory><depth-first-search>
2023-01-14 14:38:12
2
609
r0bt
75,118,691
1,506,145
How to convert a string to a numpy matrix? Inverse of numpy.array_str?
<p>I have a string I want to convert to a 2d numpy matrix, i created it by using <code>numpy.array_str</code>.</p> <pre class="lang-py prettyprint-override"><code> s = '[[ 82. 0. 0. 17.]\n [ 72. 0. 0. 30.]\n [ 79. 0. 0. 131.]\n [ 72. 0. 0. 27.]]' np.array(s) np.fromstring(s) </code></pre> <p>Howeve...
<python><numpy>
2023-01-14 14:33:28
1
5,316
user1506145
75,118,636
293,995
Open Chromium with selenium in read-mode
<p>My goal is to be able to get the main text content of a webpage without anything else. Firefox do this using with the reader view feature. It seems that Chrome haves this as experimental feature. Despite activating the feature from code, the icon doesn't show up.</p> <pre><code>from selenium import webdriver from se...
<python><selenium-chromedriver>
2023-01-14 14:23:56
1
2,631
hotips
75,118,581
5,684,405
Installing black with pipx does not install the dependency aiohttp
<p>I've installed <code>pipx</code> with <code>brew</code> and then <code>black</code> with <code>pipx</code>:</p> <pre class="lang-bash prettyprint-override"><code>$ brew install pipx ... $ pipx install black ... $ pipx list venvs are in /Users/mc/.local/pipx/venvs apps are e...
<python><python-3.x><macos><pipx>
2023-01-14 14:16:57
2
2,969
mCs
75,118,425
3,247,006
How to display values in multiple lines by indentation in Django Admin?
<p>I have <strong><code>Person</code> model</strong> below:</p> <pre class="lang-py prettyprint-override"><code># &quot;models.py&quot; from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) </code></pre> <p>Then, I put...
<python><django><django-admin><admin><indentation>
2023-01-14 13:51:27
2
42,516
Super Kai - Kazuya Ito
75,118,407
1,259,374
How do I get the next X day of the week
<p>So I have this <code>function</code> that retrieve the <code>date</code> from given days from today:</p> <pre><code>def get_date_from_today(d): tomorrow = datetime.date.today() + datetime.timedelta(days=d) return tomorrow.strftime(&quot;%Y/%m/%d&quot;) </code></pre> <p>How do I get for example the date of th...
<python><datetime><weekday>
2023-01-14 13:48:20
2
1,139
falukky
75,118,399
20,443,541
How to set up a Tor-Server (Hidden Service) as a proxy?
<p>The goal is, being able to access the proxy anonymously, such that the host (proxy) doesn't know, where the request came from (of course with credentials).</p> <p>The client should be able to acess <code>www.example.com</code> over the hosts ip, without the host knowing the clients ip.</p> <p>Here's a example reques...
<python><proxy><tor>
2023-01-14 13:46:39
2
1,159
kaliiiiiiiii
75,118,159
16,872,314
Generate specific Toeplitz covariance matrix
<p>I want to generate a statistical sample from a multidimensional normal distribution. For this I need to generate one specific kind of covariance matrix:</p> <pre><code>1 0.99 0.98 0.97 ... 0.99 1 0.99 0.98 ... 0.98 0.99 1 0.99 ... 0.97 0.98 0.99 1 ... ... ... ... ... </code></pre> <p>Is there a way to...
<python><numpy><matrix><scipy><toeplitz>
2023-01-14 13:06:37
2
720
Marcello Zago
75,118,153
11,824,828
Iterate dataframe and sum transactions by condition
<p>I have the following sample of data:</p> <pre><code> id year type num 1 1994 A 0 2 1950 A 2333 3 1977 B 4444 4 1995 B 555 1 1994 A 0 6 1955 A 333 7 2006 B 4123 6 1975 A 0 9 1999 B 123 3 1950 A 1234 ...
<python><pandas><dataframe>
2023-01-14 13:06:04
2
325
vloubes
75,118,111
4,321,525
How to iterate over a numpy array, getting two values per loop?
<p>I envision something like</p> <pre><code>import numpy as np x = np.arange(10) for i, j in x: print(i,j) </code></pre> <p>and get something like</p> <pre><code>0 1 2 3 4 5 6 7 8 9 </code></pre> <p>But I get this traceback:</p> <pre><code>Traceback (most recent call last): File &quot;/home/andreas/.local/share/...
<python><numpy><loops>
2023-01-14 13:00:21
3
405
Andreas Schuldei
75,117,522
18,806,499
E1101: Module 'mysql.connector' has no 'errors' member (no-member)
<p>I have written a python program and it's working fine on my computer, but when I'm trying to lint it with pylint and have this error: <code>E1101: Module 'mysql.connector' has no 'errors' member (no-member)</code></p> <p>I have pieces of code like this in my code:</p> <pre><code>try: ... except mysql.connector....
<python><github-actions><pylint>
2023-01-14 11:15:26
0
305
Diana
75,117,517
15,724,084
python spider scrapy cannot launch the code
<p>I before used Selenium, but now client needs Scrapy framework to be used in his project.</p> <p>I read and watched. I came to some points how to write first request spider. But I need more kind of assist.</p> <pre><code>import scrapy class QuotesSpider(scrapy.Spider): name = 'quotes' plate_num = &quot;EA66...
<python><scrapy>
2023-01-14 11:15:02
1
741
xlmaster
75,117,431
3,591,044
Splitting string on several delimiters without considering new line
<p>I have a string representing conversation turns as follows:</p> <pre><code>s = &quot;person alpha:\nHow are you today?\n\nperson beta:\nI'm fine, thank you.\n\nperson alpha:\nWhat's up?\n\nperson beta:\nNot much, just hanging around.&quot; </code></pre> <p>In plain text, it looks as follows.</p> <pre><code>person al...
<python><python-3.x><regex><string><split>
2023-01-14 10:59:44
3
891
BlackHawk
75,117,392
5,865,393
Create a default guest user on flask run
<p>How can I create a default <strong>guest</strong> user with username <code>guest</code> and password equal to <code>password</code> when I start the web server; i.e. <code>flask run</code>?</p> <blockquote> <p>The purpose of this default guest user is to be a demo user so that the actual user doesn't have to registe...
<python><authentication><flask><sqlalchemy>
2023-01-14 10:52:59
1
2,284
Tes3awy
75,117,364
5,659,324
How to store directory, sub directory and file paths in a Python Dictionary?
<p>I am developing a software which analyze excel files stored in Years directories which contains months directories and each month directory consist of excel files. Structure as shown below. <a href="https://i.sstatic.net/JZF52.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JZF52.png" alt="enter image...
<python><python-3.x><django><dictionary>
2023-01-14 10:49:59
1
659
hamid
75,117,330
1,833,328
Software lock key with Python
<p>I wrote a Python program to control a measurement instrument. This program can be transferred to other instruments, but I don't want people to do this without my agreement. I am therefore considering to use some sort of a lock key mechanism, which allows unlocking the software with a key code that is specific to a g...
<python>
2023-01-14 10:44:13
1
621
mbrennwa
75,117,011
19,826,650
Php Shell exec didn't run Python file if there are imports like pandas
<p>I have anaconda to run python,apache server localhost (phpmyadmin), php, with visual studio code. when i use shell exec without pandas is run fine, but when i want to use pandas the shell exec didn't run the python code.</p> <p>list of imports that prevent python to be executed from php:</p> <ol> <li>pandas as pd</l...
<python><php><apache><anaconda>
2023-01-14 09:40:24
0
377
Jessen Jie
75,116,920
19,504,610
Delegates the Calculation of a Property of a Superclass to its Subclass
<p>In the book, Python in a Nutshell,</p> <p>the authors claim the following code snippet is problematic:</p> <pre class="lang-py prettyprint-override"><code>class B: def f(self): return 23 g = property(f) class C(B): def f(self): return 42 c = C() print(c.g) # prints: 23, no...
<python><inheritance><properties>
2023-01-14 09:18:48
3
831
Jim
75,116,578
6,792,327
Swift: Incorrect Base64 Encoding
<p>I am attempting to convert a block of code from python and it involved encoding a json string to base64. My attempt on Swift does not produce the same base64 encoded string.</p> <p>Python:</p> <pre><code>payload_nonce = datetime.datetime(2022, 10, 10, 0, 0, 0).timestamp() payload = {&quot;request&quot;: &quot;/v1/my...
<python><swift>
2023-01-14 08:04:33
2
2,947
Koh
75,116,574
2,706,344
Interpolation using `asfreq('D')` in Multiindex
<p>The following code generates two DataFrames:</p> <pre><code>frame1=pd.DataFrame({'dates':['2023-01-01','2023-01-07','2023-01-09'],'values':[0,18,28]}) frame1['dates']=pd.to_datetime(frame1['dates']) frame1=frame1.set_index('dates') frame2=pd.DataFrame({'dates':['2023-01-08','2023-01-12'],'values':[8,12]}) frame2['d...
<python><pandas>
2023-01-14 08:02:21
1
4,346
principal-ideal-domain
75,116,527
20,240,835
Python filter larger text by quantile
<p>Assume I am process a very large text file, I have the following pseudocode</p> <pre><code>xx_valueList = [] lines=[] with line in file: xx_value = calc_xxValue(line) xx_valueList.append(xx_value) lines.append(lines) # get_quantile_value is a function return the cutoff value with a specific quantile pr...
<python><algorithm><optimization><filter><quantile>
2023-01-14 07:51:00
1
689
zhang
75,116,521
19,238,204
Check My Code.. Why Python' Sympy integration taking so long?
<p>I have been working on this to plot a function and rotating toward y and x axis. Then use SymPy to obtain the surface area.</p> <p>I try from terminal and from running the <code>.py</code> file, both taking too long for calculating the integral to obtain the surface area.</p> <p>this is my code:</p> <pre><code>impor...
<python><numpy><sympy>
2023-01-14 07:49:34
1
435
Freya the Goddess
75,116,507
17,347,824
While loop to append list or break based on value type and user input
<p>I'm trying to write a python program that asks the user to enter an integer or &quot;q&quot; (case-insensitive) to quit that will then take any integers and print the sum of the last 5.</p> <p>I have created a holding list and some counter and test variables to help with this, but I can't seem to get it to work the ...
<python>
2023-01-14 07:45:32
3
409
data_life
75,116,506
2,035,790
Improve download speed of images from s3
<p>I created a Streamlit app that gets and displays images from S3 for labeling purposes. The app is extremely slow! After using the code profiler, I discovered that the following section of code takes the most time (reaches 40-120 seconds).</p> <pre><code>for obj in my_bucket.objects.filter(Prefix=&quot;images/&quot;+...
<python><amazon-web-services><amazon-s3><boto3><streamlit>
2023-01-14 07:45:04
0
1,401
userInThisWorld
75,116,202
19,238,204
Check my Python Code to Obtain Area of the Surface Revolved About the x-axis
<p>I want to plot area of surface of</p> <p><code>(x^6 + 2)/(8x^2)</code></p> <p>with <code>1 ≤ x ≤ 3</code></p> <p>this is my Python code / MWE:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np n = 100 fig = plt.figure(figsize=(14, 7)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222, projection...
<python><numpy>
2023-01-14 06:28:24
1
435
Freya the Goddess
75,116,164
11,402,025
AWS StateMachine AccessDeniedException in step: CleanUpOnError
<p>I am getting the following error when trying to execute step function on the lambda</p> <pre><code>&quot;errorType&quot;: &quot;AccessDeniedException&quot;, &quot;errorMessage&quot;: &quot;User: arn:aws:sts::14161:assumed-role/serverlessrepo-Functi-cleanerRole/serverlessrepo-=Function-p-cleaner is not authorized t...
<python><amazon-web-services><aws-lambda><amazon-iam><aws-step-functions>
2023-01-14 06:15:07
1
1,712
Tanu
75,116,124
19,561,210
Python - Reverse Linked List Issue
<p>I have been working on the reverse linked list method for a long time and I am trying to understand why it is wrong but I can't seem to get it. The following is my function.</p> <pre class="lang-py prettyprint-override"><code>def reverse(self, head): if head is None or head.next is None: return head ...
<python><reverse>
2023-01-14 06:01:23
0
634
Jessica
75,116,047
17,696,880
How to remove the line where a specific string is found in a .txt file?
<pre class="lang-py prettyprint-override"><code>import os word_to_replace, replacement_word = &quot;&quot;, &quot;&quot; if (os.path.isfile('data_association/names.txt')): word_file_path = 'data_association/names.txt' else: open('data_association/names.txt'...
<python><python-3.x><file><replace><txt>
2023-01-14 05:43:13
0
875
Matt095
75,115,582
18,587,779
How to load toml file in python
<p>How to load toml file into a python file that my code</p> <p>python file:</p> <pre><code>import toml toml.get(&quot;first&quot;).name </code></pre> <p>toml file :</p> <pre><code>[first] name = &quot;Mark Wasfy&quot; age = 22 [second] name = &quot;John Wasfy&quot; age = 25 </code></pre>
<python><toml>
2023-01-14 03:30:03
3
318
Mark Wasfy
75,115,498
5,965,999
Connecting to a laser with Python's socket interface
<p>I'm trying to connect over ethernet to a piece of hardware (a laser) which listens for connections on a certain port. The laser's documentation on this is very minimal; the entirety of it is as follows:</p> <blockquote> <p>Ethernet TCP/IP Interface: The IP address of the laser is shown on the front panel. Touching ...
<python><sockets>
2023-01-14 03:08:37
1
2,360
Yly
75,115,453
219,976
Django EmbeddedField raises ValidationError because of renamed field
<p>I've got a Django application with <code>djongo</code> as a database driver. The models are:</p> <pre class="lang-py prettyprint-override"><code>class Blog(models.Model): _id = models.ObjectIdField() name = models.CharField(max_length=100, db_column=&quot;Name&quot;) tagline = models.TextField() class E...
<python><django><mongodb><django-models><djongo>
2023-01-14 02:53:34
4
6,657
StuffHappens
75,115,422
3,361,013
Dash app, plotly chart data outside the chart area
<p>I have written following code which updates Plotly Chart with some random values every 5 seconds, however after few seconds the new data is located outside the chart and is not visible. Is there an easy way to reset the axes everytime it's needed?</p> <p>Also how can I make this responsive so it will auto-scale to ...
<python><plotly><plotly-dash>
2023-01-14 02:44:17
1
847
Petrik
75,115,379
7,071,794
How can I disable the gradient color with kdeplot?
<p>When I run the below code, I get a figure with gradient color (from black to orange). Please look at the attached figure. Whereas I want to get a figure only with single color, orange (not figure with a gradient color). How can I do that?</p> <p><strong>My code:</strong></p> <pre><code>#!/usr/bin/python3 import nump...
<python><matplotlib><seaborn><kdeplot>
2023-01-14 02:29:28
1
437
qasim
75,115,246
17,090,926
Can you load a Polars dataframe directly into an s3 bucket as parquet?
<p>looking for something like this:</p> <p><a href="https://stackoverflow.com/questions/38154040/save-dataframe-to-csv-directly-to-s3-python">Save Dataframe to csv directly to s3 Python</a></p> <p>the api shows these arguments: <a href="https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.DataFrame.writ...
<python><dataframe><amazon-s3><parquet><python-polars>
2023-01-14 01:46:21
1
415
rnd om
75,115,154
10,318,539
How to add two Bits using single Qubit on Quantum Computer
<p>As we knew that a qubit have the capacity to store two bit at a time. I am curious to add two bits using single qubit. I try a lot but failed, please give some hints if someone know.</p> <p>Code:</p> <pre><code>from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = Quant...
<python><python-3.x><quantum-computing><qiskit>
2023-01-13 22:51:07
1
485
Engr. Khuram Shahzad
75,114,982
1,825,360
Python: Positive integral solutions for Linear Equation
<p>I want to find all POSITIVE INTEGRAL solutions for a,b for this simple, toy linear equation: a + 2b = 5 and for which the solutions are:</p> <pre><code>a|5|3|1| b|0|1|2| </code></pre> <p>I've tried a few things after going some posts here and the &quot;python-constraint&quot; module was helpful, for example:</p> <pr...
<python><equation-solving>
2023-01-13 22:24:05
1
469
The August
75,114,947
16,978,074
read a csv file in 3 columns
<p>I want to read a csv file with 3 columns: &quot;source&quot;,&quot;target&quot;,&quot;genre_ids&quot; with python</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_csv('edges1.csv',encoding=&quot;ISO-8859-1&quot;, delimiter=';;', header=None,skiprows=1, names=columns,engine=&quot;python&quot;,index_c...
<python><pandas><csv><split>
2023-01-13 22:18:29
2
337
Elly
75,114,894
17,696,880
Replace a string identified in a specific line of a .txt file by another string
<pre><code>import re, os def replace_one_line_content_with_other(input_text): word_to_replace, replacement_word = &quot;&quot;, &quot;&quot; if (os.path.isfile('data_association/names.txt')): word_file_path = 'data_association...
<python><python-3.x><file><replace><txt>
2023-01-13 22:08:11
1
875
Matt095
75,114,879
1,360,276
Python codegeneration from OpenAPI spcification
<p>Having an OpenAPI 3 specification, I'd like to generate stub code from it, defining the DTOs/serializers/deserializers, webframework-agnostic. The plan is to use this generated code not only for the client, but for the server as well. Marshmallow dataclasses models would be great, or maybe Pydantic. Any tool already...
<python><openapi>
2023-01-13 22:06:32
0
620
saabeilin
75,114,867
19,276,569
If a list is unhashable in Python, why is a class instance with list attribute not?
<p>Firstly, we have a normal list:</p> <pre><code>ingredients = [&quot;hot water&quot;, &quot;taste&quot;] </code></pre> <p>Trying to print this list's hash will expectedly raise a TypeError:</p> <pre><code>print(hash(ingredients)) &gt;&gt;&gt; TypeError: unhashable type: 'list' </code></pre> <p>which means we cannot ...
<python><list><hashable>
2023-01-13 22:04:51
1
856
juanpethes
75,114,866
8,310,504
Is there a way to wrap an numpy `ndarray` interface around an existing binary file?
<p>I have a binary network capture (<code>.pcapng</code>) file that contains video data. I am parsing the <code>.pcapng</code> with scapy and I can extract the data, but the video sequences I am working with are very large and the operations I want to perform quickly grind my machine to a halt if I load very much data...
<python><numpy><scapy><mmap><pcap>
2023-01-13 22:04:48
1
301
K. Nielson
75,114,862
1,464,515
Running idf.py runconfig only opens the "idf.py" file in vscode
<p>I installed the ESP-idf extension &quot;express install&quot; idf.py is not recognized so</p> <p><a href="https://i.sstatic.net/SGdBl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SGdBl.png" alt="enter image description here" /></a></p> <p>i added manually the environment variables IDF_PATH, IDF_TOO...
<python><vscode-extensions><esp-idf>
2023-01-13 22:04:18
1
438
Cristóbal Felipe Fica Urzúa
75,114,841
21,003,650
Debugger warning from IPython: frozen modules
<p>I created a new environment using conda and wanted to add it to jupyter-lab. I got a warning about frozen modules? (shown below)</p> <pre class="lang-none prettyprint-override"><code>$ ipython kernel install --user --name=testi2 0.00s - Debugger warning: It seems that frozen modules are being used, which may 0.00s ...
<python><ipython><python-3.11>
2023-01-13 22:01:50
2
383
Elijah
75,114,624
18,092,798
Multiline ruleorder in Snakemake
<p>I have 3 rules and their names are somewhat long. When using <code>ruleorder</code>, the line goes over my desired 80 character limit. Is it possible break up the <code>ruleorder</code> into multiple lines in such a way that the behaviour is <em>exactly</em> the same as if I wrote it all in one line?</p> <p>Example:...
<python><python-3.x><snakemake><directed-acyclic-graphs>
2023-01-13 21:28:31
3
581
yippingAppa
75,114,602
3,398,741
Poor model performances when doing multi-class classification
<h1>Context</h1> <p>I have a dataset of medical X-Rays (<a href="https://thumbs.dreamstime.com/z/x-ray-human-head-skull-side-view-cranium-medical-analysis-xray-mri-ct-diagnostic-scan-photo-ray-human-head-skull-side-view-239898982.jpg" rel="nofollow noreferrer">example</a>). I want to train a model to recognize an <a hr...
<python><tensorflow><machine-learning><keras><conv-neural-network>
2023-01-13 21:25:34
2
1,149
FrenchMajesty
75,114,570
615,743
How to batch sqlalchemy results by size
<p>I have a model <code>Post</code> and want to iterate through them in batches of 10 in a loop.</p> <p>This is what I've tried, but does not work:</p> <pre class="lang-py prettyprint-override"><code>batched_posts = Post.query.yield_for(10) for posts in batched_posts.partitions(): # error: 'Query' object has no attribu...
<python><sqlalchemy>
2023-01-13 21:20:12
1
350
ydnaklementine
75,114,565
7,071,794
could not convert string to float with sns.kdeplot
<p>I am trying to use <code>sns.kdeplot</code>to get a figure but I get the below error:</p> <pre><code>ValueError: could not convert string to float: ' 0.43082 0.45386' </code></pre> <p>Do you know how I can fix this error?</p> <p><strong>Code snippet:</strong></p> <pre><code>data=pd.read_csv('input.txt', sep=&qu...
<python><matplotlib><seaborn><kdeplot>
2023-01-13 21:19:34
1
437
qasim
75,114,510
2,889,716
FastAPI Mock is not working, Seems like that patch is not applied
<p>Would you please tell me what's wrong with this code? app.py</p> <pre class="lang-py prettyprint-override"><code>import uvicorn from fastapi import FastAPI from fastapi import status from fastapi.testclient import TestClient from app_dep import resp app = FastAPI() client = TestClient(app) def test_create_item(moc...
<python><mocking><fastapi>
2023-01-13 21:12:26
0
4,899
ehsan shirzadi
75,114,437
472,485
Sharing context between get and post
<p>what is the correct way to share context between a <code>get</code> and <code>post</code> invocation in same view in Django without sending anything anything to client? Can I do something like below?</p> <pre><code> class Req(TemplateView): @login_required def get(self, request, *args, **kwargs): r...
<python><django><post><get>
2023-01-13 21:01:36
2
22,975
Jean
75,114,410
16,491,055
Check if there exists a value in each of 3 numpy arrays, that are within an interval of x?
<p>Suppose I have 3 <code>numpy</code> arrays. It could be more than 3 arrays, however.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np INTERVAL = 2 array1 = np.array([1,5,10,15,20,25,30]) array2 = np.array([1,10,50,100,150,200,250,300]) array3 = np.array([3,8,12]) </code></pre> <p>For a given se...
<python><arrays><numpy>
2023-01-13 20:57:00
1
771
geekygeek
75,114,230
338,479
Is there a way to add a timeout to a system call in a thread?
<p>My use case: I want to call <code>fcntl.flock()</code> on a file but have a timeout. Following the recipe in <a href="https://stackoverflow.com/questions/492519/timeout-on-a-function-call/494273#494273">Timeout on a function call</a>, I wrapped my code in a <code>contextmanager</code> that implements timeouts via a ...
<python><timeout><signals>
2023-01-13 20:35:15
1
10,195
Edward Falk
75,114,215
5,304,058
how to extract data inside a bracket in pandas
<p>I have a dataframe column which has paranthesis with it. I would like to have only string inside it.</p> <pre><code>df: ID col1 1 [2023/01/06:12:00:00 AM] 2 [2023/01/06:12:00:00 AM] 3 [2023/01/06:12:00:00 AM] </code></pre> <p>Expected:</p> <pre><code>ID col1 1 2023/01/06:12:00:00 AM 2 2023/01/06:12:00:0...
<python><pandas>
2023-01-13 20:33:50
3
578
unicorn
75,114,168
1,437,877
Python structural pattern matching for string containing float
<p>How can I use structural pattern matching for the following use case:</p> <pre><code>values = [&quot;done 0.0&quot;, &quot;done 3.9&quot;, &quot;failed system busy&quot;] for v in values: vms = v.split() match vms: case ['done', float()&gt;0]: # Syntax error print(&quot;Well done&quot;) ...
<python><pattern-matching>
2023-01-13 20:26:22
2
4,089
Abbas